const puppeteer = require("puppeteer");
const { config } = require("./puppteer.config")
const { writeWeChatDoc} = require('./mongoose')



const addCookies = async (cookies_str, page, domain) => {
    let cookies = cookies_str.split(';').map(
        pair => {
            let name = pair.trim().slice(0, pair.trim().indexOf('='));
            let value = pair.trim().slice(pair.trim().indexOf('=') + 1);
            return { name, value, domain }
        });
    await Promise.all(cookies.map(pair => {
        // console.log(pair);
        return page.setCookie(pair)
    }))
}

async function main(uri) {
    const data = {
        result: null
    }
    const browser = await puppeteer.launch({
        headless: true,
        defaultViewport: null
    })
    const page = await browser.newPage()
    await addCookies(config.cookieString, page, config.domain)
    await page.setUserAgent(config.userAgent)
    page.on('response', async res => {
        if (res._url.includes('/downloads')) {
            const result = await res.text()

            data.result = result
        }


    })
    await page.goto(config.url + uri + config.urlEnd)
    await page.close()
    await browser.close()
    return data


}

async function testing(uri) {
    const data = {
        result: null
    }
    const browser = await puppeteer.launch({
        headless: true,
        defaultViewport: null
    })
    const page = await browser.newPage()

    await page.setUserAgent(config.userAgent)

    await page.goto(uri)

        const content = await page.content()
        data.result = content
        await page.close()
        await browser.close()
        return data
  
}

const weChatDataParse = async (data, date)=>{
    const result = {
        content: '',
        name: '',
        coverimg: '',
        date: ''
    }
    const name = data.result.match(/\"name\":\"(.*?)\"\,/)
    const coverimg = data.result.match(/\"coverimg\":\"(.*?)\"\,/)
    const content = data.result.match(/"content":"(.*)"}}\)/)
    result.name = unescape(name[1].replace(/\\u/g, '%u').replace(/\\/g, ''))
    result.coverimg = unescape(coverimg[1].replace(/\\u/g, '%u').replace(/\\/g, ''))
    result.content = unescape(content[1].replace(/\\u/g, '%u').replace(/\\/g, ''))
    result.date = date

    const res = await writeWeChatDoc(result)
    return res
}


module.exports = {
    main,
    testing,
    weChatDataParse
}

